﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
using System.Net.Sockets;
using System.Threading;
using System.Net;
using System.Text.RegularExpressions;
using System.Globalization;
using System.Windows.Forms;


namespace Image_recognition
{
    public class C_GetZb
    {
        public static string Devicename = "";
        public C_GetZb(string Devicename_)
        {
            Devicename = Devicename_;
        }
        #region 图像识别坐标信息反馈
        //使用IPv4地址，流式socket方式，tcp协议传递数据
        Socket soketsend = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
        Socket soketrec = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
        string recstr = ""; public string sendstr = "";
        public double pro = 9;
        public Dictionary<String, int> ZBDIC = new Dictionary<string, int>();
        int reclen;
        #region //转化数据
        /// <summary>
        /// 十六进制字符串转化为字节数组
        /// </summary>
        /// <param name="s"></param>
        /// <returns></returns>
        private static byte[] HexStringToByteArray(string s)
        {
            s = s.Replace(" ", "");
            byte[] buffer = new byte[s.Length / 2];
            for (int i = 0; i < s.Length; i += 2)
                buffer[i / 2] = (byte)Convert.ToByte(s.Substring(i, 2), 16);
            return buffer;
        }
        /// <summary>
        /// 从汉字转换到16进制
        /// </summary>
        /// <param name="s"></param>
        /// <returns></returns>
        private static string GetHexFromChs(string s)
        {
            //if ((s.Length % 2) != 0)
            //{
            //    s += " ";//空格
            //}
            System.Text.Encoding chs = System.Text.Encoding.GetEncoding("gb2312");
            byte[] bytes = chs.GetBytes(s);
            string str = "";
            for (int i = 0; i < bytes.Length; i++)
            {
                str += string.Format("{0:X}", bytes[i]);
            }
            str = "02 " + str + " 03";
            return str;
        }
        //汉字转Unicode编码
        protected string GetUnicode(string source)
        {
            byte[] bytes = Encoding.Unicode.GetBytes(source);
            StringBuilder stringBuilder = new StringBuilder();
            for (int i = 0; i < bytes.Length; i += 2)
            {
                stringBuilder.AppendFormat("\\u{0}{1}", bytes[i + 1].ToString("x").PadLeft(2, '0'), bytes[i].ToString("x").PadLeft(2, '0'));
            }
            return stringBuilder.ToString();
        }
        //Unicode转汉字
        protected string Unicode2String(string source)
        {
            return new Regex(@"\\u([0-9A-F]{4})", RegexOptions.IgnoreCase | RegexOptions.Compiled).Replace(
                         source, x => string.Empty + Convert.ToChar(Convert.ToUInt16(x.Result("$1"), 16)));
        }
        #endregion     
        public bool CameraConnetionSend(string ServerIP, string ServerPoint) //建立soket连接
        {
            bool Isconnet = false;
            try
            {
                //连接到服务器,已经连接无需再连
                if (!soketsend.Connected)
                {
                    soketsend.Close();
                    //连接到的目标IP
                    IPAddress ip_ = IPAddress.Parse(ServerIP);
                    //连接到目标IP的哪个应用(端口号！)
                    IPEndPoint point_ = new IPEndPoint(ip_, int.Parse(ServerPoint));
                    soketsend = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                    soketsend.Connect(point_);
                    //设置缓存区容量
                    soketsend.ReceiveBufferSize = 1024;
                    soketsend.SendBufferSize = 1024;
                    //Thread th = new Thread(Receivecmd);
                    //th.IsBackground = true;
                    //th.Start();
                }
                if(soketsend.Connected)
                {
                    Isconnet = true;
                }
            }
            catch (Exception err)
            {
                CsLogFun.WriteToLog(err);
                MessageBox.Show("提示：相机发送连接失败，"+err.Message);
                return false;
                //throw new Exception("提示：" + err);
            }
            return Isconnet;
        }
        public void Clientsend(string cmd)
        {
            try
            {
                byte[] buffer = Encoding.UTF8.GetBytes(cmd.ToString().Trim());
                if (soketsend.Connected)
                {
                    ZBDIC.Clear();
                    soketsend.Send(buffer);
                    TimeSpan timestart = new TimeSpan(DateTime.Now.Ticks);
                    while (ZBDIC.Count != 4)//等待坐标信息接收完
                    {
                        TimeSpan timestop = new TimeSpan(DateTime.Now.Ticks);
                        TimeSpan timedf = timestart.Subtract(timestop).Duration();
                        if (timedf.Milliseconds > 3000)
                        {
                            recstr = "超时";
                            break;
                        }
                    }
                }
            }
            catch (Exception err)
            {
                CsLogFun.WriteToLog(err);
                MessageBox.Show("提示：相机发送失败，" + err.ToString());
            }

        }
        /// <summary>
        /// 切换模板
        /// </summary>
        /// <param name="cmd"></param>
        public void Clientrec(string cmd)
        {
            try
            {
                byte[] buffer = Encoding.UTF8.GetBytes(cmd.ToString().Trim());
                if (soketsend.Connected)
                {
                    soketsend.Send(buffer);
                }
            }
            catch (Exception err)
            {
                CsLogFun.WriteToLog(err);
                MessageBox.Show("提示：相机发送失败，" + err.ToString());
            }
        }
        public bool CameraConnetionRecive(string ServerIP, string ServerPoint) //建立soket连接
        {
            bool Isconnet = false;
            try
            {
                //连接到服务器,已经连接无需再连
                if (!soketrec.Connected)
                {                       
                    soketrec.Close();        
                    //连接到的目标IP
                    IPAddress ip_ = IPAddress.Parse(ServerIP);
                    //连接到目标IP的哪个应用(端口号！)
                    IPEndPoint point_ = new IPEndPoint(ip_, int.Parse(ServerPoint));
                    soketrec = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

                    soketrec.Connect(point_);
                    //设置缓存区容量
                    soketrec.ReceiveBufferSize = 1024;
                    soketrec.SendBufferSize = 1024;
                    Thread th = new Thread(ReceiveMsg);
                    th.IsBackground = true;
                    th.Start();
                }
                if (soketrec.Connected)
                {
                    Isconnet = true;
                }
            }
            catch (Exception err)
            {
                CsLogFun.WriteToLog(err);
                MessageBox.Show("提示：相机接收连接失败，" + err.ToString());
                return false;
            }
            return Isconnet;
        }
        void ReceiveMsg()//接受坐标信息
        {
            while (true)
            {
                Thread.Sleep(1);
                try
                {
                    if (soketrec.Connected)
                    {
                        reclen = 0;
                        byte[] buffer = new byte[100];
                        if (soketrec.Connected)
                            reclen = soketrec.Receive(buffer, buffer.Length, 0);
                        else
                        {
                            continue;
                        }
                        byte[] rcebuffer = new byte[reclen];
                        for (int i = 0; i < reclen; i++)
                        {
                            rcebuffer[i] = buffer[i];
                        }
                        if (reclen > 0)
                        {
                            recstr = "";
                            recstr = Encoding.ASCII.GetString(rcebuffer);
                            int count = 0;
                            string x = "", y = "", xp = "", yp = "";
                            foreach (char c in recstr)
                            {
                                if (c == ',')
                                    count++;
                                if (count == 1 && c != ',')
                                    x += c.ToString();
                                else if (count == 2 && c != ',')
                                    y += c.ToString();
                                else if (count == 3 && c != ',')
                                    xp += c.ToString();
                                else if (count == 4 && c != ',')
                                    yp += c.ToString();
                            }
                            ZBDIC.Clear();
                            ZBDIC.Add("X", (int)(100 * (int.Parse(x) / 1000) / pro));
                            ZBDIC.Add("Y", (int)(100 * (int.Parse(y) / 1000) / pro));
                            ZBDIC.Add("XP", -(int)(100 * (int.Parse(xp) / 1000) / pro));
                            ZBDIC.Add("YP", -(int)(100 * (int.Parse(yp) / 1000) / pro));
                        }
                        else
                        {
                            continue;
                        }
                    }

                }
                catch (Exception err)
                {
                    Thread.Sleep(2000);
                   // CsLogFun.WriteToLog(err);
                   // MessageBox.Show("提示：相机通信失败，" + err.ToString());
                }
            }
        }
        void Receivecmd()//接受返回指令
        {
            while (true)
            {
                Thread.Sleep(1);
                try
                {
                    if (soketsend.Connected)
                    {
                        reclen = 0;
                        byte[] buffer = new byte[100];
                        if (soketsend.Connected)
                            reclen = soketsend.Receive(buffer);
                        else
                        {
                            //CsLogFun.WriteToLog("相机网络连接断开");
                           // MessageBox.Show("相机网络连接断开");
                            continue;
                        }
                        if (reclen > 0)
                        {
                            sendstr = Encoding.ASCII.GetString(buffer);
                        }
                    }
      
                }
                catch (Exception err)
                {
                    Thread.Sleep(2000);
                    // CsLogFun.WriteToLog(err);
                    // MessageBox.Show("提示：相机通信失败，" + err.ToString());
                }
            }
        }
        #endregion
    }
}
